<template>
  <div class="series-wrapper">
    <el-tabs v-model="tabValue" size="small" type="card">
      <el-tab-pane
        label="库存查询"
        name="kc"
      >
        <template>
          <el-autocomplete size="small" :fetch-suggestions="querySearch" class="filter-input" v-model="series"
                           clearable
          >
          </el-autocomplete>
          <el-button size="small" type="primary" class="search-btn" @click="getSeriesInfo">搜索</el-button>
          <el-button size="small" type="primary" class="search-btn" @click="exportExcel">导出excel</el-button>

          <div class="statistic">总库存：<span class="num">{{ totalKc | formatNum }}</span>，库存金额：<span class="num"
          >{{ totalKcje | formatNum }}</span></div>

          <el-table size="small" :data="seriesInfoList" header-cell-class-name="table-header">
            <el-table-column label="商品编号" prop="spbh" width="70px"></el-table-column>
            <el-table-column label="商品名称" prop="spname"></el-table-column>
            <el-table-column label="规格" prop="k" :formatter="ggFormatter" width="45px"></el-table-column>
            <el-table-column label="件数">
              <template slot-scope="scope">
                {{ Math.floor(scope.row.kc / scope.row.k) }}{{ scope.row.dw }}
              </template>
            </el-table-column>
            <el-table-column label="库存金额" prop="kcje"></el-table-column>
            <el-table-column label="散数">
              <template slot-scope="scope">
                {{ scope.row.kc % scope.row.k }}{{ scope.row.dw2 }}
              </template>
            </el-table-column>
            <el-table-column prop="xl" label="系列"></el-table-column>
          </el-table>
        </template>
      </el-tab-pane>
      <el-tab-pane
        label="出货查询"
        name="ch"
      >
        <template>
          <el-autocomplete size="small" :fetch-suggestions="querySearch" class="filter-input" v-model="series"
                           clearable
          >
          </el-autocomplete>
          <el-button size="small" type="primary" class="search-btn" @click="getSearch">搜索
          </el-button>
          <el-button size="small" type="primary" class="search-btn" @click="exportExcelCh">导出excel</el-button>
          <van-form>
            <van-field name="datetimePicker" :value="time" label="日期" placeholder="点击选择时间"
                       @click="showPicker = true" @focus="noBomBox"
            />
            <van-calendar v-model="showPicker" :min-date="minDate" type="range" allow-same-day @confirm="onConfirm"/>
          </van-form>

          <el-tabs v-model="subTabs">
            <el-tab-pane name="statistic" label="出货统计">
              <el-table size="small" :data="serieStatisticList" header-cell-class-name="table-header">
                <el-table-column label="商品编号" prop="goodId" width="70px"></el-table-column>
                <el-table-column label="商品名称" prop="goodName"></el-table-column>
                <el-table-column label="总出货数" prop="salesCount"></el-table-column>
                <el-table-column label="件数" prop="js"></el-table-column>
                <el-table-column label="件单位" prop="unitName"></el-table-column>
                <el-table-column label="散数" prop="ss"></el-table-column>
                <el-table-column label="散单位" prop="unitName2"></el-table-column>
                <el-table-column prop="xl" label="系列"></el-table-column>
              </el-table>
            </el-tab-pane>
            <el-tab-pane name="detail" label="出货明细">
              <el-table size="small" :data="seriesDetailsList" header-cell-class-name="table-header">
                <el-table-column label="商品编号" prop="spbh" width="70px"></el-table-column>
                <el-table-column label="商品名称" prop="spname"></el-table-column>
                <el-table-column label="客户名称" prop="khname"></el-table-column>
                <el-table-column label="件数" prop="js"></el-table-column>
                <el-table-column label="件单位" prop="dw"></el-table-column>
                <el-table-column label="散数" prop="xs"></el-table-column>
                <el-table-column label="散单位" prop="dw2"></el-table-column>
                <el-table-column prop="xl" label="系列"></el-table-column>
              </el-table>
            </el-tab-pane>
          </el-tabs>


        </template>
      </el-tab-pane>
    </el-tabs>

    <!-- 筛选导出列 -->
    <el-dialog title="自定义导出列" :visible.sync="exportColumnDialog" width="90vw">
      <el-checkbox-group class="export-columns-checkbox" v-model="exportStorageColumns">
        <el-checkbox label="商品编号" border></el-checkbox>
        <el-checkbox label="商品名称" border></el-checkbox>
        <el-checkbox label="规格" border></el-checkbox>
        <el-checkbox label="件数" border></el-checkbox>
        <el-checkbox label="库存金额" border></el-checkbox>
        <el-checkbox label="散数" border></el-checkbox>
        <el-checkbox label="系列" border></el-checkbox>
      </el-checkbox-group>
      <template slot="footer">
        <el-button type="primary" size="mini" plain>取消</el-button>
        <el-button type="primary" size="mini" @click="confirmExport('storage')">确定</el-button>
      </template>
    </el-dialog>


  </div>
</template>

<script>
import dayjs from 'dayjs'

export default {
  name: 'seriesQuery',
  data() {
    return {
      time: '',
      showPicker: false,
      timeArray: [],
      minDate: dayjs().subtract(3, 'year').toDate(),
      tabValue: 'kc',
      series: '',
      seriesSet: [],
      seriesInfoList: [],
      serieStatisticList: [],


      subTabs: 'statistic',
      seriesDetailsList: [],

      exportColumnDialog: false,
      exportStorageColumns: []
    }
  },
  filters: {
    formatNum(num) {
      return num.replace(/\.00$/, '')
    }
  },
  computed: {
    totalKc() {
      return this.seriesInfoList.reduce((prev, curr) => {
        return prev + curr.kc
      }, 0).toFixed(2)
    },
    totalKcje() {
      return this.seriesInfoList.reduce((prev, curr) => {
        return prev + curr.kcje
      }, 0).toFixed(2)
    }
  },
  methods: {
    async getSeriesSet() {
      let result = await this.$http.post('/goods/getGoodsSeries')
      this.seriesSet = result.data.filter(each => each !== '') || []
    },
    async getSeriesInfo() {
      if (this.series) {
        let result = await this.$http.post(`/goods/getSeriesInfo/${this.series}`)
        this.seriesInfoList = result.data || []
      }

      this.$buryingPoint('系列库存查询', this.series)
    },
    exportExcelCh() {
      if(this.subTabs === 'statistic') {
        this.getSerierOutStatisticExcel()
      } else {
        this.getSerierOutDetailExcel()
      }
    },
    // 导出出货统计excel
    async exportExcel() {

      this.exportColumnDialog = true
      this.exportStorageColumns = ['商品编号', '商品名称', '规格', '件数', '库存金额', '散数', '系列']

      // if (this.series) {
      //   this.$buryingPoint('系列库存查询-导出excel', this.series)
      //   window.open(`api/goods/exportSeriesExcel/${this.series}`, '_self')
      // }
    },
    confirmExport(type) {
      if(type === 'storage') {

        const map = {
          '商品编号': 'spbh',
          '商品名称': 'spname',
          '规格': 'k',
          '件数': 'js',
          '库存金额': 'kcje',
          '散数': 'ss',
          '系列': 'xl'
        }

        if (this.series) {
          this.$buryingPoint('系列库存查询-导出excel', this.series)
          // window.open(`api/goods/exportSeriesExcel/${this.series}`, '_self')
          this.$http.post(`goods/exportSeriesExcel/${this.series}`, this.exportStorageColumns.map(v => map[v]), {
            responseType: 'blob'
          })
        }
      }
    },
    ggFormatter(row, column, cellValue) {
      return cellValue.replace(/\.0$/, '')
    },
    querySearch(queryString, cb) {
      let results = queryString ? this.seriesSet.filter(this.createFilter(queryString)) : this.seriesSet
      results = results.map(item => {
        return {
          value: item,
          label: item
        }
      })
      cb(results)
    },
    createFilter(queryString) {
      return (item) => {
        return (item.toLowerCase().indexOf(queryString.toLowerCase()) === 0)
      }
    },
    noBomBox(Event) {
      document.activeElement.blur()
    },
    onConfirm(date) {
      console.log(date, 'date')
      this.timeArray = date
      this.time = `${date[0].getMonth() + 1}/${date[0].getDate()} -- ${date[1].getMonth() + 1}/${date[1].getDate()}`
      this.showPicker = false
    },
    getSearch() {
      if(this.subTabs === 'statistic') {
        this.getSerierOutStatistic()
      } else {
        this.getSeriesOutDetail()
      }
    },
    getSerierOutStatistic() {
      if (this.series) {
        const loading = this.$loading({
          text: '正在计算中...此统计方式耗时较长，大约需要5～10秒，请耐心等候'
        })
        this.$http.post(`/goods/getSeriesOutStatistic`, {
          seriesName: this.series,
          startTime: dayjs(this.timeArray[0]).startOf('day').format('YYYY-MM-DD HH:mm:ss'),
          endTime: dayjs(this.timeArray[1]).endOf('day').format('YYYY-MM-DD HH:mm:ss')
        }).then(result => {
          this.serieStatisticList = result.data || []
        }).finally(() => {
          loading.close()
          this.$buryingPoint('系列出仓查询-统计', {
            seriesName: this.series,
            startTime: dayjs(this.timeArray[0]).startOf('day').format('YYYY-MM-DD HH:mm:ss'),
            endTime: dayjs(this.timeArray[1]).endOf('day').format('YYYY-MM-DD HH:mm:ss')
          })
        })
      }
    },
    getSeriesOutDetail() {
      const loading = this.$loading({
        text: '正在计算中...此统计方式耗时较长，大约需要5～10秒，请耐心等候'
      })
      this.$http.post('/goods/getSeriesOutDetail', {
        seriesName: this.series,
        startTime: dayjs(this.timeArray[0]).startOf('day').format('YYYY-MM-DD HH:mm:ss'),
        endTime: dayjs(this.timeArray[1]).endOf('day').format('YYYY-MM-DD HH:mm:ss')
      }).then(result => {
        this.seriesDetailsList = result.data || []
      }).finally(() => {
        loading.close()
        this.$buryingPoint('系列出仓查询-明细', {
          seriesName: this.series,
          startTime: dayjs(this.timeArray[0]).startOf('day').format('YYYY-MM-DD HH:mm:ss'),
          endTime: dayjs(this.timeArray[1]).endOf('day').format('YYYY-MM-DD HH:mm:ss')
        })
      })
    },
    getSerierOutStatisticExcel() {
      if (this.series) {
        const loading = this.$loading({
          text: '正在计算中...此统计方式耗时较长，大约需要5～10秒，请耐心等候'
        })
        this.$http.post('/goods/getSeriesOutStatisticExcel', {
          seriesName: this.series,
          startTime: dayjs(this.timeArray[0]).startOf('day').format('YYYY-MM-DD HH:mm:ss'),
          endTime: dayjs(this.timeArray[1]).endOf('day').format('YYYY-MM-DD HH:mm:ss')
        }, {
          responseType: 'blob'
        }).finally(() => {
          loading.close()
          this.$buryingPoint('系列出仓查询-导出excel', {
            seriesName: this.series,
            startTime: dayjs(this.timeArray[0]).startOf('day').format('YYYY-MM-DD HH:mm:ss'),
            endTime: dayjs(this.timeArray[1]).endOf('day').format('YYYY-MM-DD HH:mm:ss')
          })
        })
      }
    },
    getSerierOutDetailExcel() {
      if (this.series) {
        const loading = this.$loading({
          text: '正在计算中...此统计方式耗时较长，大约需要5～10秒，请耐心等候'
        })
        this.$http.post('/goods/getSeriesOutDetailExcel', {
          seriesName: this.series,
          startTime: dayjs(this.timeArray[0]).startOf('day').format('YYYY-MM-DD HH:mm:ss'),
          endTime: dayjs(this.timeArray[1]).endOf('day').format('YYYY-MM-DD HH:mm:ss')
        }, {
          responseType: 'blob'
        }).finally(() => {
          loading.close()
          this.$buryingPoint('系列出仓查询-导出excel明细', {
            seriesName: this.series,
            startTime: dayjs(this.timeArray[0]).startOf('day').format('YYYY-MM-DD HH:mm:ss'),
            endTime: dayjs(this.timeArray[1]).endOf('day').format('YYYY-MM-DD HH:mm:ss')
          })
        })
      }
    }
  },
  mounted() {
    this.getSeriesSet()
  }
}
</script>

<style scoped lang="scss">
.series-wrapper {
  max-width: 900px;
  width: 100%;
  padding: 10px;

  .filter-input {
    width: calc(100% - 160px);
  }

  .search-btn {
    margin-left: 6px;
  }

  .statistic {
    margin: 10px 0;
    font-size: 12px;
    color: #999999;

    .num {
      color: #ef714c;
      font-weight: bold;
    }
  }

  .el-table {
    ::v-deep {
      .table-header {
        background-color: #eaeaea;
      }
    }
  }
}
</style>

<style lang="scss">
.export-columns-checkbox {
  display: flex;
  flex-direction: column;
  .el-checkbox.is-bordered {
    margin-left: 0;
    margin-right: 0;
    margin-bottom: 10px;
  }
  .el-checkbox.is-bordered+.el-checkbox.is-bordered {
    margin-left: 0;
  }
}
</style>
